﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CheckoutOrder.aspx.cs" Inherits="EarringsRecommendationWeb.CheckoutOrder" %>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>Checkout Order</title>
    <!-- Bootstrap Core CSS -->
    <link href="css/bootstrap.css" rel="stylesheet">
    <link href="css/bootstrap-theme.css" rel="stylesheet" />

    <script type="text/javascript" src="js/jquery-2.1.1.min.js"></script>
    <script type="text/javascript" src="js/bootstrap.js"></script>   
    <script type="text/javascript" src="js/bootbox.js"></script>
    <script type="text/javascript">       
        $(function () {
            $('#form-nav-bar').load('navbar.html');
            $.getScript("js/Login.js", function () { });
        });
    </script>
    <script src="js/toast.js" type="text/javascript"></script>
    <script src="js/formatmoney.js"></script>
</head>
<body>
    
    <div class="alert alert-success" role="alert" style="display:none; z-index: 1000; position: absolute; left:0px; top: 50px;">
      <span>populate alert</span>
    </div>
    <div class="alert alert-warning" role="alert" style="display:none; z-index: 1000; position: absolute; left:0px; top: 50px;">
      <span>populate alert</span>
    </div>
    <!-- Navigation -->
    <nav id="form-nav-bar" class="navbar navbar-inverse navbar-static-top" role="navigation">        
        <!-- /.container -->
    </nav>
    <form runat="server" id="checkoutOrder">
    <!-- Page Content -->
    <div class="container">
        <div class="container" >
            <address id="member-zone"> 
                <div >
                    <label>ชื่อ-นามสกุล</label>         
                    <p style="display: inline-block; margin-left: 20px;" id="member-name">member_name</p>
                </div>
                <div>
                    <label>อีเมล์</label>           
                    <p style="display: inline-block; margin-left: 20px;" id="member-email">email</p>
                </div>
                <div>
                    <label>ที่อยู่</label>          
                    <p style="display: inline-table; margin-left: 20px;" id="member-address">address</p>
                </div>            
            </address>
            <p id="please-login" class="hidden">ยังไม่ได้ล็อกอิน กรุณาล็อกอิน</p> 
        </div>
        <div class="col-md-12">
            <label>วันที่รับสินค้า :</label>
            <p style="display: inline-block; margin-left: 20px;" id="receive-date"></p>
            <button type="button" class="btn btn-success pull-right" id="btn-confirm">ยืนยันรายการสินค้า</button>
        </div>
        
        <div class="col-md-12" style="padding-top: 20px;">
            <div class="list-group" id="list-order">            
            </div>
        </div>
    </div>
    <!-- /.container -->
    <div class="container">
        <hr>
        <!-- Footer -->
        <footer>
            <div class="row">
                <div class="col-lg-12">
                    <p>
                        Copyright &copy; Your Website 2015
                    </p>
                </div>
            </div>
        </footer>
    </div>
    <!-- /.container -->
    </form>
<!-- Bootstrap Core JavaScript -->
    <script type="text/javascript">
        $(window).load(function () {            
            if (typeof EarringsInOrder === 'undefined') return;
            setTimeout(function () { displayItemQuantity(); }, 1000);
            getReceiveDate();
            buildTable();
            
            if (typeof Member === 'undefined' || Member[0] === null) {
                $('#member-zone').addClass('hidden');
                $('#please-login').removeClass('hidden');
            } else {
                $('#member-zone').removeClass('hidden');
                $('#please-login').addClass('hidden');
                var member = Member[0][0];
                document.getElementById('member-name').innerHTML = member.Name;
                document.getElementById('member-email').innerHTML = member.Email;
                document.getElementById('member-address').innerHTML = member.Address;
            }
        });

        function getReceiveDate(){
            var receivedate = ReceiveDate[0][1];
            $('#receive-date').html(receivedate);
        }

        function buildTable() {

            var array = EarringsInOrder[0];
            var element = '';
            for (var i = 0; i < array.length; i++) {

                element += '<a href="#" class="list-group-item prd" style="width: 100%;">';
                element += '    <div class="form-inline container">';                
                element += '        <div class="col-md-2">';
                element += '            <img src="' + array[i].imgPath + '" class="media-object thumbnail" style="width: 120px;">';
                element += '            <button type="button" class="btn btn-warning btn-sm" id="btn-' + array[i].er_code + '">ลบ</button>';
                element += '        </div>';
                element += '        <div class="col-md-5">';
                element += '            <h4 class="list-group-item-heading">' + array[i].er_name + '</h4>';
                element += '            <p class="list-group-item-text" value="' + array[i].er_price + '" id="price-' + array[i].er_code + '">' + Number(array[i].er_price).formatMoney() + ' บาท' + '</p> </br>';
                var txtClass = '';
                if (array[i].er_status === 'รอประกอบ') {
                    txtClass = 'text-danger';
                } else {
                    txtClass = 'text-success';
                }
                element += '            <p class="list-group-item-text">สถานะสินค้า : ' + '<span class= "' + txtClass + '">' + array[i].er_status + '</span>' + '</p>';
                element += '            <p class="list-group-item-text">รายละเอียด : ' + array[i].er_detail + '</p>';
                element += '        </div>';
                element += '        <div class="col-md-2">';
                element += '            <div class="input-group">';
                element += '              <span class="input-group-addon">จำนวน</span>';
                element += '              <input type="number" class="form-control catch" min="1" value="' + array[i].er_qty + '" id="qty-' + array[i].er_code + '">';
                element += '            </div>';
                element += '        </div>';
                element += '        <div class="col-md-2">';
                element += '            <p class="form-control-static">ราคารวม</p>';
                element += '            <p class="form-control-static pull-right" id="total-' + array[i].er_code + '">' + Number(array[i].er_qty * array[i].er_price).formatMoney() + ' บาท' + '</p>';
                element += '        </div>';               
                element += '    </div>';
                element += '</a>';
            }

            var list = document.getElementById('list-order');
            list.innerHTML = '';
            list.innerHTML = element;
            getTotal();
        }

        //
        //click to hilight list
        //
        $(document).on('click', '.list-group-item', function (e) {
            e.preventDefault();
            $(this).addClass('active');
        });
        $(document).on('blur', '.list-group-item', function (e) {
            e.preventDefault();
            $(this).removeClass('active');
        });

        //
        //change quantity and display receive date
        //
        $(document).on('change', '.catch', function (e) {
            e.preventDefault();
            var controlId = this.id.split('-')[1] + '-' + this.id.split('-')[2];
            document.getElementById('total-' + controlId).innerHTML = Number(this.value * document.getElementById('price-' + controlId).getAttribute('value')).formatMoney() + ' บาท';
            getTotal();
        });        

        var earringsArray;
        function getTotal() {
            var array = EarringsInOrder[0];
            var temp = 0;
            earringsArray = [];
            for (var i = 0; i < array.length; i++) {
                var objEarrings = { ERCode: '', Qty: 0 };

                var code = array[i].er_code;

                objEarrings.ERCode = code;

                var pPrice = document.getElementById('price-' + code);
                var price = 0;
                if (pPrice) {
                    price = parseFloat(pPrice.getAttribute('value'));
                    var quantity = parseInt($('#qty-' + code).val());
                    temp += price * quantity;

                    objEarrings.Qty = quantity;
                }

                earringsArray.push(objEarrings);
            }

            var element = '';
            element += '<a href="#" class="list-group-item" style="width: 100%;" id="grand-total">';
            element += '    <div class="form-inline container">';
            element += '        <div class="col-md-2">';            
            element += '        </div>';
            element += '        <div class="col-md-5">';            
            element += '        </div>';
            element += '        <div class="col-md-2">';
            element += '        </div>';
            element += '        <div class="col-md-2">';
            element += '            <p class="form-control-static">รวมทั้งสิ้น</p>';
            element += '            <p class="form-control-static pull-right" id="txt-grand-total">' + Number(temp).formatMoney() + ' บาท' + '</p>';
            element += '        </div>';
            element += '    </div>';
            element += '</a>';

            var grandTotal = document.getElementById('grand-total');
            if (!grandTotal) {
                var list = document.getElementById('list-order');
                list.innerHTML += element;
            } else {
                $('#txt-grand-total').html(Number(temp).formatMoney() + ' บาท');
            }

            //calculate receive date
            $.ajax({
                type: "POST",
                dataType: "json",
                crossDomain: true,
                url: "http://localhost:49331/WSRestFul.asmx/GetReceiveDate",
                data: { data: JSON.stringify(earringsArray) }
            }) //ajax
            .done(function (data) {
                if ($('#receive-date').html() != data.result) {
                    Toast.init({
                        "selector": ".alert-success"
                    });
                    Toast.show("มีการแก้ไขจำนวน วันที่รับสินค้าจึงเปลียนเป็น <b>" + data.result + "</b>");
                    $('#receive-date').html(data.result);
                }

            }) //done
            .fail(function (data) {
                bootbox.dialog({
                    title: 'Fatal Error',
                    message: '<div class="alert alert-danger" role="alert"><strong>Error in GetReceiveDate !!!</strong></div>'
                });//boobox
            }) //fail

        }

        $(document).on('click', '.btn-sm', function (e) {
            e.preventDefault();
            var array = EarringsInOrder[0];            

            var code = $(this).attr('id').split('-')[1] + '-' + $(this).attr('id').split('-')[2];
            removeItem(code, $(this));                                  
        });

        function removeItem(erCode, $button) {
            $.ajax({
                type: "POST",
                dataType: "json",
                crossDomain: true,
                url: "http://localhost:49331/WSRestFul.asmx/RecalQtyConfirm",
                data: { er_code: erCode }
            }) //ajax
            .done(function (data) {
                Toast.init({
                    "selector": ".alert-success"
                });
                Toast.show("ลบออกจากรายการ เรียบร้อย !!!", $button.offset().top-30);

                var tempQty = 0;
                for (var i = 0; i < data.length; i++) {
                    tempQty += parseInt(data[i].Qty);
                }

                if (tempQty === 0) {
                    window.location = 'home.aspx';
                } else {
                    qty[0] = tempQty;
                    setTimeout(function () {
                        $button.parent().parent().parent().remove();
                    }, 300);
                    setTimeout(function () {
                        getTotal();
                    }, 300);
                    setTimeout(function () {
                        displayItemQuantity();
                    }, 300);
                }

            }) //done
            .fail(function (data) {
                bootbox.dialog({
                    title: 'Fatal Error',
                    message: '<div class="alert alert-danger" role="alert"><strong>Error in connection !!!</strong></div>'
                });//boobox
            }) //fail
        }

        var btnConfirm = document.getElementById('btn-confirm');
        btnConfirm.onclick = function () {
            
            if (!$('#please-login').hasClass('hidden')) {

                Toast.init({
                    "selector": ".alert-warning"
                });
                Toast.show("กรุณาล็อกอิน !!!");
                return;
            }

            var catchInput = document.getElementsByClassName('catch');
            var str = '';
            var arr = [];
            for (var i = 0; i < catchInput.length; i++) {
                var er_code = catchInput[i].id.split('-')[1] + '-' + catchInput[i].id.split('-')[2];
                var qty = catchInput[i].value;
                
                var obj = { ERCode: er_code, Qty: qty };
                arr.push(obj);                
            }

            //ajax call
            $.ajax({
                type: "POST",
                dataType: "json",
                crossDomain: true,
                url: "http://localhost:49331/WSRestFul.asmx/ConfirmOrder",
                data: { orderdata: JSON.stringify(arr) }
            }) //ajax
            .done(function (data) {

                if (data.result === 'success') {
                    Toast.init({
                        "selector": ".alert-success"
                    });
                    Toast.show("ยืนยันการสั่งซื้อ เรียบร้อย !!!");
                    setTimeout(function () {
                        window.location = "ConfirmOrder.aspx";
                    }, 2000);
                }
                
            }) //done
            .fail(function (data) {
                bootbox.dialog({
                    title: 'Fatal Error',
                    message: '<div class="alert alert-danger" role="alert"><strong>Error in connection !!!</strong></div>'
                });//boobox
            }) //fail
        }

    </script>
</body>
</html>